package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"oct25-tasks/cache"
	"oct25-tasks/models"
	"oct25-tasks/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")
	if username == "" || password == "" {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "账号或密码不能为空",
		})
		return
	}
	redis_key := "User_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "账号已封锁",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "查询失败，用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour)
			c.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁1小时",
			})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
}
